﻿using System;
using System.Collections.Generic;

namespace FrameWork
{
    public class ModuleManager : Singleton<ModuleManager>
    {

        private Dictionary<string, BaseModule> dicModules = null;

        public override void Init()
        {
            dicModules = new Dictionary<string, BaseModule>();
        }
        #region Get Module

        public BaseModule Get(string key)
        {
            if (dicModules.ContainsKey(key))
            {
                return dicModules[key];
            }
            return null;
        }


        public T Get<T>() where T : BaseModule
        {
            //Type可以拿到对应的键
            Type t = typeof(T);
            return Get(t.ToString()) as T; //强转
            //             if (dicModules.ContainsKey(t.ToString()))
            //             {
            //                 return dicModules[t.ToString()] as T;
            //             }
            //             return null;

        }
        #endregion
       

        #region Register
        //注册
        public void Register(BaseModule module)
        {
            Type t = module.GetType();
            Register(t.ToString(), module);
        }


        //注册
        public void Register(string key, BaseModule module)
        {
            if (!dicModules.ContainsKey(key))
            {
                dicModules.Add(key, module);
            }
        }
        #endregion
  

        #region UnRegister

        //注销单个
        public void UnRegister(BaseModule module)
        {
            Type t = module.GetType();
            UnRegister(t.ToString());
        }

        //注销单个
        public void UnRegister(string key)
        {
            if (dicModules.ContainsKey(key))
            {
                BaseModule module = dicModules[key];
                module.Release();
                dicModules.Remove(key);
            }
        }

        //注销全部
        public void UnRegisterAll()
        {
            List<string> _keyList = new List<string>(dicModules.Keys);
            for (int i = 0; i < _keyList.Count; i++)
            {
                UnRegister(_keyList[i]);
            }
            dicModules.Clear();
        }
        #endregion





    }
}

